package edu.pku.hawk.sandbox;

import java.util.Date;
import java.util.Random;
import flex.messaging.MessageBroker;
import flex.messaging.messages.AsyncMessage;
import flex.messaging.messages.Message;
import flex.messaging.services.MessageService;
import flex.messaging.services.ServiceAdapter;
import flex.messaging.util.UUIDUtils;

public class LocationServiceAdapter extends ServiceAdapter {
	Random random;
	PointGenerator thread;

	public LocationServiceAdapter() {
		random = new Random();
		System.out.println("Adapter initilized");
	}

	public void start() {
		if (thread == null) {
			System.out.println("Adapter started");
			thread = new PointGenerator();
			thread.start();
		}
	}

	public void stop() {
		System.out.println("Adapter stopped");
		thread.running = false;
		thread = null;
	}

	private SensorHistoryData generatePoint() {

		int value = random.nextInt(100);

		SensorHistoryData data = new SensorHistoryData("" + new Date(), value);

		return data;
	}

	public class PointGenerator extends Thread {
		public boolean running = true;

		public void run() {
			String clientId = UUIDUtils.createUUID();
			MessageBroker msgBroker = MessageBroker.getMessageBroker(null);
			while (running) {
				AsyncMessage msg = new AsyncMessage();
				msg.setDestination("LocationServicePush");
				msg.setClientId(clientId);
				SensorHistoryData data = generatePoint();
				msg.setMessageId(UUIDUtils.createUUID());
				msg.setBody(data);
				msgBroker.routeMessageToService(msg, null);
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					System.out.println("Exception");
					e.printStackTrace();
				}
			}
		}
	}

	@Override
	public Object invoke(Message msg) {
		if (msg.getBody().equals("New")) {
			System.out.println("Adapter received new");
			return generatePoint();
		} else {
			//System.out.println("Adapter sending message");
			AsyncMessage newMessage = (AsyncMessage) msg;
			MessageService msgService = (MessageService) getDestination()
					.getService();
			msgService.pushMessageToClients(newMessage, true);
		}
		return null;
	}
}